import { Injectable } from '@nestjs/common'
import { SessionAnalytics } from './models/session-analytics.model'
import { Repository } from 'typeorm'
import { InjectRepository } from '@nestjs/typeorm'
import { EventAnalytics } from './models/event-analytics.model'
import { EventTypes } from './event-types.enum'
import { IncomingRequestCfProperties } from './interfaces/incoming-request-cf.interface'
import { CryptographyService } from '@boticord/auth'

@Injectable()
export class AnalyticsService {
  constructor(
    @InjectRepository(SessionAnalytics) private readonly sessions: Repository<SessionAnalytics>,
    @InjectRepository(EventAnalytics) private readonly events: Repository<EventAnalytics>,
    private readonly crypto: CryptographyService,
  ) {}

  async track(
    type: EventTypes,
    ip: string,
    userAgent: string,
    affectedID?: string,
    userID?: string,
    cf?: IncomingRequestCfProperties,
  ):
    Promise<{ s: SessionAnalytics; e: EventAnalytics }>
  {
    let session = await this.sessions.findOne({ where: { ip } })
    if (!session) {
      session = new SessionAnalytics()
      session.ip = ip
    }
    if (!session.asn && cf) {
      session.city = cf.city
      session.country = cf.country
      session.region = cf.region
      session.timezone = cf.timezone
      session.isp = cf.asOrganization
      session.asn = cf.asn
    }
    await this.sessions.save(session)

    const now = Date.now()
    const event = new EventAnalytics()
    event.type = type
    event.userAgent = userAgent
    event.timestamp = now
    event.affectedID = affectedID
    event.session = session
    event.userID = userID ? this.crypto.aesEncrypt(userID) : undefined
    await this.events.save(event)

    return { s: session, e: event }
  }

}
